package com.itheima.bigevent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.bigevent.mapper.ArticleMapper;
import com.itheima.bigevent.pojo.Article;
import com.itheima.bigevent.pojo.PageBean;
import com.itheima.bigevent.pojo.User;
import com.itheima.bigevent.service.ArticleService;
import com.itheima.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public int add(Article article) {
        // 获取当前用户
        User currentUser = ThreadLocalUtil.get();

        article.setCreateUser(currentUser.getId());
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        return articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
        // 创建PageBean对象
        PageBean<Article> pageBean = new PageBean<>();

        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        // 调用Mapper查询
        User currentUser = ThreadLocalUtil.get();
        List<Article> articleList = articleMapper.list(currentUser.getId(), categoryId, state);

        // 将查询结果分页
        // Page类继承自ArrayList类，Page中提供了方法，可以获取PageHelper分页查询后得到的总记录条数和当前页的数据，如果不强制数据类型转换，则无法通过父类调用子类中的方法，即无法获取总记录条数和当前页的数据
        Page<Article> page = (Page<Article>) articleList;
        // 将数据填充到PageBean对象中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);

        return pageBean;
    }
}
